﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WGMClient.WGMSvc;
using WGMClient.Controls;
using WGMClient.HelperClasses;
using WGMClient.Properties;

namespace WGMClient.Views
{
    /// <summary>
    /// Interaction logic for LoginView.xaml
    /// </summary>
    public partial class LoginView : UserControl, HelperClasses.IMessageListener
    {
        public LoginView()
        {
            InitializeComponent();
            HelperClasses.Registry.RegisterListener(this);
            _loginSelector.AssociatedTab = _loginTab;
            _createAccSelector.AssociatedTab = _createAccTab;
            _recoverAccSelector.AssociatedTab = _recoverAccTab;
            _rememberLoginChk.IsChecked = HelperClasses.Registry.Settings.RememberCreds;
            if (HelperClasses.Registry.Settings.RememberCreds)
            {
                _usernameTB.Text = HelperClasses.Registry.Settings.LastUsername;
                _passwordTB.Password = HelperClasses.Registry.Settings.LastPassword;
            }
        }

        void _mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                foreach (TabItem item in e.AddedItems)
                {
                    (item.Tag as BackgroundTextBlock).IsSelected = true;
                }
                foreach (TabItem item in e.RemovedItems)
                {
                    (item.Tag as BackgroundTextBlock).IsSelected = false;
                }
            }
            catch { }
        }


        public void NotifyServerMessage(WGMSvc.WGMMessage message)
        {
            this.Dispatcher.Invoke
            (
                new Action
                (
                    delegate
                    {
                        this.IsEnabled = true;
                        switch (message.MessageType)
                        {
                            case WGMClient.WGMSvc.MessageTypes.USER_LOGON_DENIED:
                                HelperClasses.Registry.MainWindow.SetDropDownMessage("Incorrect Username/Password", Colors.White, Colors.OrangeRed,"_loginview_");
                                break;
                            case WGMClient.WGMSvc.MessageTypes.USER_LOGON_SUCCESS:
                                HelperClasses.Registry.MainWindow.ClearDropDownMessage("_loginview_");
                                HelperClasses.Registry.Username = _usernameTB.Text;
                                HelperClasses.Registry.Password = _passwordTB.Password;
                                HelperClasses.Registry.MyState = ClientState.ONLINE;
                                break;
                            case WGMClient.WGMSvc.MessageTypes.USER_CREATION_SUCCESS:
                                HelperClasses.Registry.MainWindow.SetDropDownMessage("User creation successful, logging in...", Colors.White, Colors.LimeGreen, "_loginview_");
                                _usernameTB.Text = _createUsernameTB.Text;
                                _passwordTB.Password = _createPasswordTB.Password;
                                OnLogin(this, null);
                                break;
                            case WGMClient.WGMSvc.MessageTypes.USER_CREATION_DENIED:
                                HelperClasses.Registry.MainWindow.SetDropDownMessage(message.Message as string, Colors.White, Colors.OrangeRed, "_loginview_");
                                break;
                        }
                        
                    }
                )
            );

        }
        public void NotifyLocalMessage(LocalMessage message)
        {
            this.Dispatcher.Invoke
            (
                new Action
                (
                    delegate
                    {
                        if (message.MessageType == LocalMessageTypes.CONNECTION_FAULTED)
                            this.IsEnabled = true;
                    }
                )
            );
        }
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            HelperClasses.HelperFunctions.SlideIn(this, this.ActualWidth * -1, 0, TimeSpan.FromSeconds(0.2));

        }

        private void OnLogin(object sender, MouseButtonEventArgs e)
        {
            HelperClasses.Registry.Username = _usernameTB.Text;
            if (_rememberLoginChk.IsChecked == true)
            {
                HelperClasses.Registry.Settings.LastPassword = _passwordTB.Password;
                HelperClasses.Registry.Settings.LastUsername = _usernameTB.Text;
                HelperClasses.Registry.Settings.RememberCreds = true;
            }
            else
            {
                HelperClasses.Registry.Settings.LastPassword = "";
                HelperClasses.Registry.Settings.LastUsername = "";
                HelperClasses.Registry.Settings.RememberCreds = false;
            }
            HelperClasses.HelperFunctions.SaveSettings();
            HelperClasses.Registry.MainWindow.SetDropDownMessage("Logging in...", Colors.White, Colors.LimeGreen,"_loginview_");
            HelperClasses.Registry.Engine.SendMessageToServer(new WGMSvc.WGMMessage() { SenderLogon = _usernameTB.Text, Message = _passwordTB.Password, MessageType = WGMClient.WGMSvc.MessageTypes.USER_REQUEST_LOGON, SenderTimeStamp = DateTime.Now });
            this.IsEnabled = false;

        }

        private void OnPasswordKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                OnLogin(this, null);
            }
        }

        private void OnCreateAccount(object sender, MouseButtonEventArgs e)
        {
            HelperClasses.HelperFunctions.SlideOut(_mainTabControl, this.ActualHeight,0,TimeSpan.FromSeconds(0.2));
            _createAccSelector.IsSelected = true;
            HelperClasses.Registry.MainWindow.ClearDropDownMessage("_loginview_");
            HelperClasses.HelperFunctions.SlideIn(_mainTabControl, this.ActualWidth * -1, 0, TimeSpan.FromSeconds(0.2));

        }

        private void OnRecoverAccount(object sender, MouseButtonEventArgs e)
        {

        }

        private void OnCancelCreateAccount(object sender, MouseButtonEventArgs e)
        {
            HelperClasses.HelperFunctions.SlideOut(_mainTabControl, this.ActualHeight, 0, TimeSpan.FromSeconds(0.2));
            _loginSelector.IsSelected = true;
            HelperClasses.Registry.MainWindow.ClearDropDownMessage("_loginview_");
            HelperClasses.HelperFunctions.SlideIn(_mainTabControl, this.ActualWidth * -1, 0, TimeSpan.FromSeconds(0.2));
        }

        private void OnCreateAccountSubmit(object sender, MouseButtonEventArgs e)
        {
            if (_createUsernameTB.Text.Trim() == "")
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Enter a valid username", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }
            if (_createPasswordTB.Password.Trim() == "")
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Enter a valid password", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }
            if (_createPasswordTB.Password != _createConfirmPasswordTB.Password)
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Passwords do not match", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }

            if (_createSecureQTB.Text.Trim() == "")
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Enter a valid security question", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }
            if (_createSecureATB.Password.Trim() == "")
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Enter a valid security answer", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }
            if (_createSecureATB.Password != _createConfirmSecureATB.Password)
            {
                HelperClasses.Registry.MainWindow.SetDropDownMessage("Security answers do not match", Colors.White, Colors.OrangeRed, "_loginview_");
                return;
            }
            HelperClasses.Registry.MainWindow.SetDropDownMessage("Creating account...", Colors.White, Colors.BlueViolet, "_loginview_");
            this.IsEnabled = false;

            WGMMember newMember = new WGMMember();
            newMember.Username = _createUsernameTB.Text.Trim().ToLower();
            newMember.Password = _createPasswordTB.Password;
            newMember.JoinDate = DateTime.Now;
            newMember.DisplayName = _createUsernameTB.Text;
            newMember.DisplayStatus = "New user";
            newMember.Email = _createEmailTB.Text;
            newMember.SecureQ = _createSecureQTB.Text.Trim();
            newMember.SecureA = _createSecureATB.Password;
            newMember.FontSize = 10;
            newMember.FontFace = "Verdana";

            WGMMessage newMessage = new WGMMessage();
            newMessage.SenderLogon = _createUsernameTB.Text.Trim().ToLower() ;
            newMessage.MessageType = MessageTypes.USER_REQUEST_CREATION;
            newMessage.Message = newMember;
            newMessage.SenderTimeStamp = DateTime.Now;

            HelperClasses.Registry.Username = newMember.Username;
            HelperClasses.Registry.Password = newMember.Password;
            HelperClasses.Registry.Engine.SendMessageToServer(newMessage);

        }

        private void OnCreateKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                OnCreateAccountSubmit(sender, null);
            }
        }
    }
}
